<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>百宝箱</title>
  </head>
  <body>
    <link rel="stylesheet" href="main.css"/>
    <div class="panel" id="panel">
      <div id="content"></div>
    </div>
    <iframe id="viewer" name="viewer" allow="fullscreen; xr-spatial-tracking;"></iframe>
    <script >
      const content = document.getElementById( 'content' );
      const viewer = document.getElementById( 'viewer' );

      const links = {};
		  const validRedirects = new Map();
      const container = document.createElement('div');

      let selected = null;

      init();

		  async function init() {

        content.appendChild( container );
        const files = await ( await fetch( './files.json' ) ).json();

        for ( const key in files ) {

          const section = files[ key ];

          const header = document.createElement( 'h2' );
          header.textContent = key;
          header.setAttribute( 'data-category', key );
          container.appendChild( header );

          for ( let i = 0; i < section.length; i ++ ) {

            const file = section[ i ];

            const link = createLink( file );
            container.appendChild( link );

            links[ file ] = link;
            validRedirects.set( file, file + '.html' );

          }
        }

      }
      
      function createLink( file ) {

        const template = `
          <div class="card">
            <a href="${file}.html" target="viewer">
              <div class="title">${getName( file )}</div>
            </a>
          </div>
        `;

        const link = createElementFromHTML( template );

        link.querySelector( 'a[target="viewer"]' ).addEventListener( 'click', function ( event ) {

          if ( event.button !== 0 || event.ctrlKey || event.altKey || event.metaKey ) return;

          selectFile( file );

        } );

        return link;

      }

      function selectFile( file ) {

        if ( selected !== null ) links[ selected ].classList.remove( 'selected' );

        links[ file ].classList.add( 'selected' );

        window.location.hash = file;
        viewer.focus();
        viewer.style.display = 'unset';

        selected = file;

        }
      
      function getName( file ) {

        const name = file.split( '_' );
        name.shift();
        return name.join( ' / ' );

      }

      function createElementFromHTML( htmlString ) {

        const div = document.createElement( 'div' );
        div.innerHTML = htmlString.trim();
        return div.firstChild;

      }
    </script>
  </body>
</html>